package com.bmps.springcloud.insuredmicroservice.service.underwrite.strategy.insurance;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 工厂方式从配置文件中获取险种投核保校验类
 * @author lyw
 * @date 2019-07-30 09:54:10
 */
public class InsuranceStrategyFactory {

    private static Logger logger = LoggerFactory.getLogger(InsuranceStrategyFactory.class);

    private static ConcurrentHashMap<String, InsuranceStrategy> insuranceMap = new ConcurrentHashMap<>();

    static {
        try {
            Resource resource = new ClassPathResource("insuredstrategy.properties");
            InputStream inputStream = resource.getInputStream();
            Properties properties = new Properties();
            properties.load(inputStream);
            for (String key : properties.stringPropertyNames()) {
                InsuranceStrategy insuranceStrategy = (InsuranceStrategy) Class.forName(properties.getProperty(key)).newInstance();
                Arrays.stream(key.split(",")).forEach(s -> {
                    insuranceMap.put(s, insuranceStrategy);
                    logger.info("add key: " + s + ", new instance:" + insuranceStrategy);
                });
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
        } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) {
            logger.error(e.getMessage());
        }
    }
    public static InsuranceStrategy getInsuranceStrategy(String key) {
        return insuranceMap.get(key);
    }
}
